import cv2


def CatchUsbVideo(window_name, camera_idx):
    cv2.namedWindow(window_name)

    # 采集器
    grabber = cv2.VideoCapture(camera_idx)

    # 分类器
    faceCascade = cv2.CascadeClassifier("model/haarcascade_frontalface_alt2.xml")

    # 人脸方框颜色
    facesColor = (0, 255, 0)

    while grabber.isOpened():
        # 读取一帧数据
        ok, frame = grabber.read()
        if not ok:
            break

        # 将当前帧转换成灰度图像
        grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # 人脸方框
        faceRects = faceCascade.detectMultiScale(grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))

        # 大于0则检测到人脸
        if len(faceRects) > 0:
            # 单独框出每一张人脸
            for faceRect in faceRects:
                x, y, w, h = faceRect
                # 绘制人脸方框
                cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), facesColor, 2)

        # 显示图像
        cv2.imshow(window_name, frame)

        # 等待
        c = cv2.waitKey(10)
        # 退出
        if c & 0xFF == ord('q'):
            break

    # 释放
    grabber.release()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    CatchUsbVideo("camera", 2)
